
//  SISSTabBarController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/10.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSTabBarController.h"
#import "SISSNavigationController.h"
#import "SISSBaseViewController.h"

#import "SISSNavigationController.h"
#import "AppDelegate.h"

#import "zhFullView.h"
#import <zhPopupController/zhPopupController.h>

#import "SISSHouseResourceEnrollViewController.h"
#import "SISSPassengerResourceEnrollViewController.h"
#import "SISSHouseResourceCooperationViewController.h"
#import "SISSPassengerResourceCooperationViewController.h"
#import "SISSEnrollPropertyCheckViewController.h"
#import "SISSTenantEnrollViewController.h"
#import "SISSLoginViewController.h"
#import "SISSChangePasswordViewController.h"
#import <AudioToolbox/AudioToolbox.h>

// 引入环信头文件
#import <Hyphenate/Hyphenate.h>
#import <UserNotifications/UserNotifications.h>
// 本地通知信息
#import <EaseConvertToCommonEmoticonsHelper.h>
#import <EaseEmotionManager.h>

#import "SISSNetworkingManager+Message.h"

#import <JPUSHService.h>

#define kTabbarHeight self.tabBar.bounds.size.height

#define kAddViewWidth self.tabBar.bounds.size.height
#define kAddViewHeight self.tabBar.bounds.size.height
#define kAddBtnWidth kAddViewWidth
#define kAddBtnHeight self.tabBar.bounds.size.height

#define  kContentFrame  CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - kTabbarHeight)
#define  kDockFrame CGRectMake(0, self.view.frame.size.height - kTabbarHeight, self.view.frame.size.width, kTabbarHeight)

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;

@interface SISSTabBarController ()<SISSTabBarDelegate,UINavigationControllerDelegate,EMClientDelegate,EMChatManagerDelegate>

/**
 加号视图
 */
@property (weak, nonatomic) UIView *tabAddView;
/**
 加号按钮
 */
@property (weak, nonatomic) UIButton *tabItemAddButton;

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

/* isFirst */
@property (assign, nonatomic) BOOL isFirst;

@end

@implementation SISSTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加自定义tabBar
    [self addCustomTabBar];
    
    // 添加控制器
    [self addControllers];
    
    
//    [self.customTabBar showBadgeOnMessage];
    
    // 设置别名
    [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",[SISSUserAccount shared].sp_id] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        NSLog(@" %zd…%@===%zd" ,iResCode,iAlias,seq);
        
    } seq:1];
    
    [[SISSPublicSingleton shared] addObserver:self forKeyPath:@"unreadCount" options:NSKeyValueObservingOptionNew context:NULL];
    
    
    [kNetworkManager requestIMAccountWithSuccess:^(NSDictionary *userData) {
        
        NSLog(@"userData %@",userData);
        
        [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
        [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
        [SISSUserAccount shared].imAccount = userData[@"username"];
        [self loginIMChatWithUserData:userData];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

/// 登录环信
- (void)loginIMChatWithUserData:(NSDictionary *)userData {
    [[EMClient sharedClient] loginWithUsername:userData[@"username"]
                                      password:userData[@"password"]
                                    completion:^(NSString *aUsername, EMError *aError) {
                                        if (!aError) {
                                            //                                                [[EMClient sharedClient].options setIsAutoLogin:YES];
                                            EMError *error = nil;
                                            EMPushOptions *pushOptions = [[EMClient sharedClient] pushOptions];
                                            pushOptions.displayStyle = EMPushDisplayStyleMessageSummary; // 显示消息内容
                                            //    pushOptions.displayStyle = EMPushDisplayStyleSimpleBanner; // 显示“您有一条新消息”
                                            [pushOptions setNoDisturbStatus:EMPushNoDisturbStatusClose];
                                            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                                [[EMClient sharedClient] updatePushOptionsToServer];
                                            });
                                            [self setBadgeCount];
                                            NSLog(@"环信登陆成功");
                                        } else {
                                            NSLog(@"环信登陆失败");
                                            [self loginIMChatWithUserData:userData];
                                        }
                                    }];
}


- (void)setBadgeCount {
    
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += [conversation unreadMessagesCount];
    }
    [SISSPublicSingleton shared].unreadCount = unreadCount;
    
}

- (void)messagesDidReceive:(NSArray *)aMessages {
    
    [self setBadgeCount];
    
    for (EMMessage *message in aMessages) {
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        
        switch (state) {
            case UIApplicationStateActive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateInactive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateBackground:
                [self showNotificationWithMessage:message];
                break;
            default:
                break;
        }
        
    }
}

- (void)playSoundAndVibration {
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    // 系统声音
    AudioServicesPlaySystemSound(1007);
    // 收到消息时，震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
}

- (void)showNotificationWithMessage:(EMMessage *)message {
    
    // 提醒，可以根据需要进行弹出，比如显示消息详情，或者是显示“您有一条新消息”
    EMMessageBody *messageBody = message.body;
    NSString *messageStr = @"";
    switch (messageBody.type) {
        case EMMessageBodyTypeImage:{
            messageStr = NSLocalizedString(@"[图片]", @"[image]");
        } break;
        case EMMessageBodyTypeText:{
            // 表情映射。
            NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                        convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
            messageStr = didReceiveText;
            if ([message.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                messageStr = @"[动画表情]";
            }
        } break;
        case EMMessageBodyTypeVoice:{
            messageStr = NSLocalizedString(@"[语音]", @"[voice]");
        } break;
        case EMMessageBodyTypeLocation: {
            messageStr = NSLocalizedString(@"[位置]", @"[location]");
        } break;
        case EMMessageBodyTypeVideo: {
            messageStr = NSLocalizedString(@"[视频]", @"[video]");
        } break;
        case EMMessageBodyTypeFile: {
            messageStr = NSLocalizedString(@"[文件]", @"[file]");
        } break;
        default: {
        } break;
    }
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    BOOL playSound = NO;
    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
        self.lastPlaySoundDate = [NSDate date];
        playSound = YES;
    }
    
    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) { // ios 10
        // 设置触发时间
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.badge = @([SISSPublicSingleton shared].unreadCount);
        if (playSound) {
            content.sound = [UNNotificationSound defaultSound];
        }
        
        content.body = messageStr;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
        
    } else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = messageStr;
        notification.alertAction = @"Open";
        notification.timeZone = [NSTimeZone defaultTimeZone];
        if (playSound) {
            notification.soundName = UILocalNotificationDefaultSoundName;
        }
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"unreadCount"]) {
        if ([SISSPublicSingleton shared].unreadCount != 0) {
            self.customTabBar.badge = [SISSPublicSingleton shared].unreadCount;
            [self.customTabBar showBadgeOnMessage];
            
        } else {
            
            [self.customTabBar hideBadgeOnMessage];
        }
        [UIApplication sharedApplication].applicationIconBadgeNumber = [SISSPublicSingleton shared].unreadCount;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


/**
 在dealloc中取消监听
 */
- (void)dealloc {
    
    [[SISSPublicSingleton shared] removeObserver:self forKeyPath:@"unreadCount"];
}

/*!
 *  当前登录账号在其它设备登录时会接收到该回调
 */
- (void)userAccountDidLoginFromOtherDevice {
    
    if (!self.isFirst) { // 只让此调用一次
        self.isFirst = YES;
        [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
            NSLog(@"rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);
            
        } seq:1];
    }
    
    NSString *str = @"您的帐户在另一端登录，您已被迫下线。如非本人操作请立即修改密码！";
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSForegroundColorAttributeName: COLOR(0x334A60), NSParagraphStyleAttributeName: paragraphStyle}];
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alertC setValue:attr forKey:@"attributedMessage"];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"修改密码" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        SISSChangePasswordViewController *changePSDVC = [[SISSChangePasswordViewController alloc] init];
        changePSDVC.url = URL_CHANGE_PASSWORD;
        SISSNavigationController *nav = [[SISSNavigationController alloc] initWithRootViewController:changePSDVC];
        [self presentViewController:nav animated:YES completion:nil];
        NSLog(@"修改密码");
    }];
    if (iOS9Later) { // 适配iOS8
        // 修改按钮
        [cancelAction setValue:COLOR(0x74A4FE) forKey:@"titleTextColor"];
    }
    
    [alertC addAction:cancelAction];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [UIApplication sharedApplication].keyWindow.rootViewController = [[SISSLoginViewController alloc] init];
        NSLog(@"重新登录");
    }];
    [alertC addAction:okAction];
    
    [self presentViewController:alertC animated:YES completion:nil];
}

/**
 添加自定义tabBar
 */
- (void)addCustomTabBar {
    
    SISSTabBar *customTabBar = [[SISSTabBar alloc] initWithFrame:self.tabBar.bounds];
    
    // 设置代理
    customTabBar.delegate = self;
    customTabBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:customTabBar];
    
    // 记录属性
    self.customTabBar = customTabBar;
    
    // 添加➕按钮
    [self addRegistrationButton];
}


/**
 添加➕按钮
 */
- (void)addRegistrationButton {
    
    // 添加➕按钮
    UIButton *tabItemAddButton = [[UIButton alloc]init];
    [tabItemAddButton setBackgroundImage:[UIImage imageNamed:@"tab_add"] forState:UIControlStateNormal];
    [tabItemAddButton setBackgroundImage:[UIImage imageNamed:@"tab_add_sel"] forState:UIControlStateHighlighted];
    [tabItemAddButton sizeToFit];
    
    tabItemAddButton.tag = 2;
    // ➕按钮点击事件
    [tabItemAddButton addTarget:self action:@selector(tabItemAddBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customTabBar addSubview:tabItemAddButton];
    
    [tabItemAddButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.customTabBar);
    }];
    
    // 记录属性
    self.tabItemAddButton = tabItemAddButton;
}



/**
 ➕按钮点击事件
 */
- (void)tabItemAddBtnClick {
    zhFullView *full = [self fullView];
    full.didClickFullView = ^(zhFullView * _Nonnull fullView) {
        [self.zh_popupController dismiss];
    };

    full.didClickItems = ^(zhFullView *fullView, NSInteger index) {

        self.zh_popupController.didDismiss = ^(zhPopupController * _Nonnull popupController) {

            // 跳转不同的控制器
            SISSNavigationController *navc;
            switch (index) {
                case 0: {
                    SISSHouseResourceEnrollViewController *vc = [[SISSHouseResourceEnrollViewController alloc] init];
                    vc.title = @"房源登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 1: {
                    SISSPassengerResourceEnrollViewController *vc = [[SISSPassengerResourceEnrollViewController alloc] init];
                    vc.title = @"客源登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 2: {
                    SISSHouseResourceCooperationViewController *vc = [[SISSHouseResourceCooperationViewController alloc] init];
                    vc.title = @"房源合作";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 3: {
                    SISSPassengerResourceCooperationViewController *vc = [[SISSPassengerResourceCooperationViewController alloc] init];
                    vc.title = @"客源合作";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 4: {
                    SISSEnrollPropertyCheckViewController *vc = [[SISSEnrollPropertyCheckViewController alloc] init];
                    vc.title = @"产权验证";
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                case 5: {
                    SISSTenantEnrollViewController *vc = [[SISSTenantEnrollViewController alloc] init];
                    vc.title = @"租客登记";
                    vc.isRegistration = YES;
                    navc = [[SISSNavigationController alloc] initWithRootViewController:vc];
                }
                    break;
                default:
                    break;
            }

            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate.window.rootViewController presentViewController:navc animated:YES completion:nil];

        };

        [fullView endAnimationsCompletion:^(zhFullView *fullView) {
            [self.zh_popupController dismiss];
        }];
    };

    self.zh_popupController = [zhPopupController popupControllerWithMaskType:zhPopupMaskTypeWhiteBlur];
    self.zh_popupController.allowPan = YES;
    [self.zh_popupController presentContentView:full];
}

- (zhFullView *)fullView {
    zhFullView *fullView = [[zhFullView alloc] initWithFrame:self.view.frame];
    
    NSArray *array = @[@"1", @"2", @"3", @"4", @"5", @"6"];
    NSArray *titleNames = @[@"房源登记", @"客源登记", @"房源合作", @"客源合作", @"出租登记", @"租客登记"];
    NSMutableArray *models = [NSMutableArray arrayWithCapacity:array.count];
    for (NSString *string in array) {
        zhIconLabelModel *item = [zhIconLabelModel new];
        item.icon = [UIImage imageNamed: string];
        item.text = titleNames[[string integerValue] - 1];
        [models addObject:item];
    }
    fullView.models = models;
    return fullView;
}

#pragma mark - SISSTabBarDelegate
- (void)changeNav:(NSInteger)from to:(NSInteger)to {
    
    self.selectedIndex = to;
}

- (void)gestureControl{

//    [self.registrationViewController.view removeFromSuperview];

}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    UIViewController *root = navigationController.viewControllers.firstObject;
    if (viewController != root) {
        // 更改导航控制器的高度
        navigationController.view.frame = self.view.bounds;
        // 从HomeViewController移除
        [self.customTabBar removeFromSuperview];
        [self.tabAddView removeFromSuperview];
        
        // 调整tabbar的Y值
        CGRect dockFrame = self.customTabBar.frame;
        CGRect tabAddViewFrame = self.tabAddView.frame;
        
        if ([root.view isKindOfClass:[UIScrollView class]]) {
            
            UIScrollView *scrollview = (UIScrollView *)root.view;
            dockFrame.origin.y = scrollview.contentOffset.y + root.view.frame.size.height - kTabbarHeight;
            tabAddViewFrame.origin.y = scrollview.contentOffset.y + root.view.frame.size.height -kTabbarHeight - (kAddViewHeight - kAddViewWidth);
            
        } else {
            
            tabAddViewFrame.origin.y = root.view.frame.size.height -kAddViewHeight;
            dockFrame.origin.y = root.view.frame.size.height - kTabbarHeight;
        }
        self.customTabBar.frame = dockFrame;
        
        self.tabAddView.frame = tabAddViewFrame;
        
        // 添加dock到根控制器界面
        [root.view addSubview:self.customTabBar];
        [root.view addSubview:self.tabAddView];
    }
}



- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
    UIViewController *root = navigationController.viewControllers[0];
    if (viewController == root) {
        // 更改导航控制器view的frame
        navigationController.view.frame = kContentFrame;
        
        // 让Dock从root上移除
        [self.customTabBar removeFromSuperview];
        [self.tabAddView removeFromSuperview];
        
        //customTabBar添加dock到HomeViewController
        self.customTabBar.frame = kDockFrame;
        [self.view addSubview:self.customTabBar];
        
        
        self.tabAddView.center = CGPointMake(SCREEN_WIDTH*0.5, SCREEN_HEIGHT-(kAddViewHeight*0.5));
        self.tabAddView.bounds = CGRectMake(0, 0, kAddViewWidth, kAddViewHeight);
        [self.view addSubview:self.tabAddView];
    }
    
}



/**
 添加控制器
 */
- (void)addControllers {
    
    NSArray *controllersName = @[@"SISSHomeViewController", @"SISSProgressViewController", @"SISSRegistrationViewController", @"SISSMessageViewController"];
    
    NSMutableArray *controllers = [NSMutableArray arrayWithCapacity:controllersName.count];
    for (int i = 0; i < controllersName.count; i++) {
        
        UIViewController *viewController = [[NSClassFromString(controllersName[i]) alloc] init];
        SISSNavigationController *navController = [[SISSNavigationController alloc] initWithRootViewController:viewController];
        navController.delegate = self;
        [controllers addObject:navController];
    }
    
    UIStoryboard *mineStoryboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    UIViewController *vc = [mineStoryboard instantiateInitialViewController];
    SISSNavigationController *navController = [[SISSNavigationController alloc] initWithRootViewController:vc];
    [controllers addObject:navController];
    
    self.viewControllers = controllers;
}



@end
